package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    //分类分页查询
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize){
        //条件构造
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //升序排序
        lambdaQueryWrapper.orderByAsc(Category::getSort);
        //分页查询
        Page<Category> categoryPage = new Page<>(page,pageSize);
        categoryService.page(categoryPage,lambdaQueryWrapper);
        return R.success(categoryPage);
    }
    //新增分类
    @PostMapping
    public R<String> save(@RequestBody Category category){
        categoryService.save(category);

        return R.success("添加成功！！！");
    }

    //分类删除
    @DeleteMapping
    public R<String> delete(Long id){
//        categoryService.removeById(id);
        boolean flag = categoryService.remove(id);
        if(flag){
            categoryService.removeById(id);
            return R.success("删除成功！！！");
        }
        return R.error("删除错误！！！");
    }


    //通过id来回显数据
    @GetMapping
    private R<Category> updateById(Long id){

        Category byId = categoryService.getById(id);

        return R.success(byId);
    }
    //修改
    @PutMapping
    public R<String> update(@RequestBody Category category){

     categoryService.updateById(category);

     return R.success("修改成功");
    }

//    查询菜品分类列表数据
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //通过查询category中的type是否有相等来进行分类
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.eq(category.getType()!=null,Category::getType,category.getType());

        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(lambdaQueryWrapper);

        return R.success(list);

    }










}
